package com.jxit0573.android.lib.net;

import java.io.File;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @author jia
 */
public class UploadRequest extends OkHttpRequest {

    public UploadRequest(String url, Object tag, Map<String, String> headers, Map<String, Object> params) {
        super(url, tag, headers, params);
    }

    @Override
    protected RequestBody buildRequestBody() {
        MultipartBody.Builder multiBuilder = new MultipartBody.Builder();
        multiBuilder.setType(MultipartBody.FORM);
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() == null) {
                    multiBuilder.addFormDataPart(entry.getKey(), "");
                } else {
                    if (entry.getValue() instanceof File) {
                        RequestBody body = RequestBody.create(
                                MediaType.parse("application/octet-stream"),
                                (File) entry.getValue());
                        multiBuilder.addFormDataPart("file", entry.getKey(), body);
                    } else {
                        multiBuilder.addFormDataPart(entry.getKey(), "" + entry.getValue());
                    }
                }
            }
        }
        return multiBuilder.build();
    }

    @Override
    protected Request buildRequest(RequestBody requestBody) {
        return builder.post(requestBody).build();
    }
}
